package com.mars.admin.modules.goods.service.impl;

import com.mars.admin.modules.goods.entity.GoodsCategory;
import com.mars.admin.modules.goods.mapper.GoodsCategoryMapper;
import com.mars.admin.modules.goods.service.GoodsCategoryService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.mars.admin.modules.goods.entity.table.GoodsCategoryTableDef.GOODS_CATEGORY;

/**
 * 商品分类服务实现类
 *
 * @author Mars
 * @version 1.0
 * @date 2025-01-07
 */
@Service
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> implements GoodsCategoryService {

    @Override
    public List<GoodsCategory> getCategoryTree() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(GOODS_CATEGORY.IS_DELETED.eq(0))
                .and(GOODS_CATEGORY.STATUS.eq(1))
                .and(GOODS_CATEGORY.IS_SHOW.eq(1))
                .orderBy(GOODS_CATEGORY.SORT_ORDER.asc(), GOODS_CATEGORY.ID.asc());
        return list(queryWrapper);
    }

    @Override
    public List<GoodsCategory> getChildrenByParentId(Long parentId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(GOODS_CATEGORY.PARENT_ID.eq(parentId))
                .and(GOODS_CATEGORY.IS_DELETED.eq(0))
                .and(GOODS_CATEGORY.STATUS.eq(1))
                .and(GOODS_CATEGORY.IS_SHOW.eq(1))
                .orderBy(GOODS_CATEGORY.SORT_ORDER.asc(), GOODS_CATEGORY.ID.asc());
        return list(queryWrapper);
    }

    @Override
    public GoodsCategory getByCategoryCode(String categoryCode) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(GOODS_CATEGORY.CATEGORY_CODE.eq(categoryCode))
                .and(GOODS_CATEGORY.IS_DELETED.eq(0));
        return getOne(queryWrapper);
    }

    @Override
    public boolean existsCategoryCode(String categoryCode, Long excludeId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(GOODS_CATEGORY.CATEGORY_CODE.eq(categoryCode))
                .and(GOODS_CATEGORY.IS_DELETED.eq(0));
        if (excludeId != null) {
            queryWrapper.and(GOODS_CATEGORY.ID.ne(excludeId));
        }
        return count(queryWrapper) > 0;
    }
} 